<template>
  <div class="file-view-box" :style="{ paddingRight: (formShare && showType != 'document_html') ? '0px' : '8px' }"
    :class="[formShare && 'share-file-view-box', isScreen && 'file-view-screen']">
    <div class="empty-box" v-if="!showType"></div>
    <imgViewer v-if="showType == 'img'" :viewerList="[videoSource]"></imgViewer>
    <iframe id="mainIframe" v-if="showType == 'iframe' && refreshFlag" class="iframe" :src="videoSource" ref="iframe"
      :class="[!isOffice(docInfo.type) && 'iframe-class']"></iframe>
    <pdfViewerPage id="mainIframe" v-if="showType == 'pdf' && refreshFlag" :printTitle="docInfo.name" ref="viewFileRef"
      :pdfUrl="videoSource" @renderFinish="renderFinish"></pdfViewerPage>
    <el-input v-if="tetVal && showType == 'utf-8' && refreshFlag" autosize type="textarea" readonly ref="textareaInput"
      v-model="tetVal" class="textareaInput"></el-input>
    <div v-if="showType == 'error' && refreshFlag" style="display: flex;align-items: center;justify-content: center;">
      <img :src="noReadPng" />
    </div>
    <div v-if="showType == 'video' && refreshFlag" style="position: relative;">
      <Vue3VideoPlay width="100%" :height="getVideoheight" ref="viewFileRef" :src="videoSource" :autoplay="false"
        preload="nona" :title="docInfo.name" />
    </div>
    <topology v-if="showType == 'document_flow' && refreshFlag" ref="viewFileRef" :id="docInfo.id" :readonly="true"
      :formShare="formShare" @renderFinish="renderFinish"></topology>
    <aomao-editor v-if="showType == 'document_html' && refreshFlag" ref="viewFileRef" :isRead="true" :id="docInfo.id"
      :formShare="formShare" @setMenuList="setMenuList" :isWritingPreview="isWrit" @renderFinish="renderFinish" />
    <MindElixir v-if="showType == 'document_map' && refreshFlag" ref="viewFileRef" :id="docInfo.id" :readonly="true"
      :formShare="formShare" @renderFinish="renderFinish"></MindElixir>
    <xmind-map v-if="showType == 'xmind' && refreshFlag" ref="viewFileRef" :id="docInfo.id" :isRead="true"
      :formShare="formShare" @renderFinish="renderFinish"></xmind-map>
    <LuckySheet v-if="showType == 'document_xlsx' && refreshFlag" ref="viewFileRef" :id="docInfo.id" :readonly="true"
      :formShare="formShare" @renderFinish="renderFinish" :isWritingPreview="isWrit"></LuckySheet>
    <editorMd v-if="showType == 'md' && refreshFlag" ref="viewFileRef" :id="docInfo.id" :mdIsPreview="true"
      :formShare="formShare" @renderFinish="renderFinish" @setMenuList="setMenuList"></editorMd>
    <epubView v-if="showType == 'epub' && refreshFlag" ref="viewFileRef" :id="docInfo.id"
      @renderFinish="renderFinish"></epubView>
    <ofdView v-if="showType == 'ofd' && refreshFlag" ref="viewFileRef" :id="docInfo.id" :formShare="formShare"
      :nodeInfo="docInfo" @renderFinish="renderFinish"></ofdView>
    <monitorOffice :option="officeOption" ref="viewFileRef" v-if="showType == 'office' && refreshFlag"></monitorOffice>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  watch,
  onMounted,
  nextTick,
  getCurrentInstance,
  computed,
  ComponentInternalInstance
} from 'vue'
import Vue3VideoPlay from 'vue3-video-play'

import { getFileUrl } from "@/api/common";
import { Base64 } from "js-base64";
// import { require } from '@/utils/require'
import { isOffice, isValidUTF8 } from '@/utils/util'
import editorMd from '@/components/editorMd/index.vue'
import ofdView from '@/components/ofd/index.vue'
import epubView from '@/components/epub/index.vue'
import LuckySheet from "@/components/luckySheet/index.vue";
import xmindMap from '@/components/xmind-map/index.vue'
import MindElixir from "@/components/mindElixir/index.vue";
import AomaoEditor from "@/components/aomaoEditor/index.vue";
import topology from "@/components/topology/index.vue";
import monitorOffice from '@/components/monitor-office/monitorOffice.vue'
import pdfViewerPage from '@/components/pdfViewerPage/index.vue'
import imgViewer from '@/components/imgViewer/index.vue'
import useUserInfoStore from '@/store/userInfo';
import noReadPng from '@/assets/images/common/noread.png'
import { useHookI18n } from '@/hooks/i18n'
const { $t } = useHookI18n()
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const userStore = useUserInfoStore()

const emit = defineEmits(["refreshScrollState", 'setMenuList', 'renderFinish'])
const refreshFlag = ref(true)
const props = defineProps({
  docInfo: {
    type: Object,
    default() {
      return {}
    }
  },
  formShare: {
    type: Boolean,
    default: false
  },
  isWrit: {
    type: Boolean,
    default: false
  },
  isScreen: {
    type: Boolean,
    default: false
  },
  isDir: {
    type: Boolean,
    default: false
  }
})
watch(() => props.docInfo.id, () => {
  init()
})
const showType = ref('')
const videoSource = ref('')
const isIframe = ref(false)
const isOfd = ref(false)
const tetVal = ref('')
const viewFileRef = ref()
const officeOption = ref<any>({})
const BASE_URL = (window.location.protocol + pluginConfig.officeCallBackUrl.substring(pluginConfig.officeCallBackUrl.indexOf('://') + 1)) || ''

onMounted(() => {
  init()
})
const getVideoheight = computed(() => {
  if (props.formShare) {
    return (document.body.clientHeight - 68) + 'px'
  } else {
    if (props.isDir) {
      return (document.body.clientHeight - 102) + 'px'
    } else {
      return (document.body.clientHeight - 252) + 'px'
    }
  }
})
function init() {
  showType.value = ''
  videoSource.value = ''
  isIframe.value = false
  isOfd.value = false
  tetVal.value = ''
  if (props.docInfo.type == 'document_upload' || isOffice(props.docInfo.type)) {
    if (['epub'].indexOf(props.docInfo.nameSuffix) != -1) {
      showType.value = 'epub'
      emit('refreshScrollState')
    } else if (['ofd'].indexOf(props.docInfo.nameSuffix) != -1) {
      showType.value = 'ofd'
      emit('refreshScrollState')
    } else {
      getFileUrl({ id: props.docInfo.id, isOnlyOffice: true, isTemplate: false }).then(res => {
        if (res.data.code == 0) {
          if (['jpg', 'jpeg', 'png', 'gif'].indexOf(props.docInfo.nameSuffix) != -1) {
            showType.value = 'img'
            videoSource.value = res.data.data.url
          } else if (["avi", "wmv", "mpg", "mpeg", "mov", "rm", "ram", "swf", "flv", "mp4", "mp3", "wma", "avi", "rm", "rmvb", "flv", "mpg", "mkv"].indexOf(props.docInfo.nameSuffix) != -1) {
            showType.value = 'video'
            videoSource.value = res.data.data.url
          } else if (['pdf'].indexOf(props.docInfo.nameSuffix) != -1) {
            let fileUrl = res.data.data.url, fileArr = res.data.data.url.split("//")
            if (fileArr[0] != window.location.protocol) {
              fileArr[0] = window.location.protocol
              fileUrl = fileArr.join("//")
            }
            videoSource.value = fileUrl
            console.log(videoSource.value)
            showType.value = 'pdf'
          } else if (['txt'].indexOf(props.docInfo.nameSuffix) != -1) {
            let xhr = new XMLHttpRequest();
            xhr.open("get", res.data.data.url, true);
            xhr.send();
            xhr.onreadystatechange = function () {
              if (xhr.readyState === 4 && xhr.status === 200) {
                if (isValidUTF8(xhr.responseText)) {
                  showType.value = 'utf-8'
                } else {
                  showType.value = 'error'
                }
                tetVal.value = xhr.responseText
              }
            }
          } else {
            if (isOffice(props.docInfo.type) && ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'csv'].indexOf(props.docInfo.nameSuffix) != -1) {
              showType.value = 'office'
              officeOption.value.id = res.data.data.key
              officeOption.value.title = ' '
              officeOption.value.fileType = props.docInfo.nameSuffix
              officeOption.value.isEdit = false
              officeOption.value.comment = false
              officeOption.value.mode = 'view'
              officeOption.value.url = res.data.data.url
              officeOption.value.editUrl = `${BASE_URL}/mgr/document/only/office?id=${props.docInfo?.id}&userId=${userStore.userInfo?.id}&userName=${userStore.userInfo?.realName}&isTemple=false&tenantId=${userStore.userInfo?.tenantId}`
              nextTick(() => {
                viewFileRef.value.init()
              })
            } else {
              showType.value = 'iframe'
              console.log(encodeURIComponent(Base64.encode('file:///etc/passwd')))
              let url = encodeURIComponent(Base64.encode(res.data.data.url))
              videoSource.value = `${window.pluginConfig.documentUrl}/onlinePreview?url=${url}`
            }
          }
          emit('refreshScrollState')
          emit('renderFinish')
        }
      })
    }
  } else {
    if (props.docInfo.type == "url_address") {
      showType.value = 'iframe'
      videoSource.value = props.docInfo.urlAddress
      emit('renderFinish')
    } else {
      showType.value = props.docInfo.type
    }
    emit('refreshScrollState')
  }
}
function setMenuList(val: any, nodeList: any) {
  emit("setMenuList", val, nodeList)
}
function renderFinish() {
  emit("renderFinish")
}
function changeResize() {
  nextTick(() => {
    viewFileRef.value?.changeResize && viewFileRef.value?.changeResize()
  })
}
function refreshFile() {
  refreshFlag.value = false
  setTimeout(() => {
    refreshFlag.value = true
  }, 10)
  init()
}
function downFile(downType: any) {
  proxy.$openJvsMessage({
    message: $t('message.message.fileDownloading')
  })
  viewFileRef.value?.downFile(props.docInfo, downType)
}
defineExpose({
  changeResize,
  refreshFile,
  downFile
})
</script>
<style lang="scss" scoped>
.file-view-box {
  width: 100%;
  padding-right: 8px;
  position: relative;
  box-sizing: border-box;

  .empty-box {
    min-height: 650px;
  }

  #mainIframe {
    width: 100%;
    height: calc(100vh - 200px);
    border: none;
  }
}

.share-file-view-box {
  .empty-box {
    min-height: calc(100vh - 74px);
  }

  #mainIframe {
    width: 100%;
    height: calc(100vh - 74px);
    border: none;
  }

  .image-viewer {
    width: 100%;
    height: calc(100vh - 74px);
  }

  .view-file-office {
    height: calc(100vh - 74px) !important;
  }
}

.file-view-screen {
  padding-right: 0px !important;

  .empty-box {
    min-height: calc(100vh - 60px);
  }

  #mainIframe {
    width: 100%;
    height: calc(100vh - 60px);
    border: none;
  }

  .image-viewer {
    width: 100%;
    height: calc(100vh - 60px);
  }

  .view-file-office,
  .mind-map-read,
  .topology-view-box,
  .view-file-mindElixir {
    height: calc(100vh - 60px) !important;
  }

  ::v-deep(.ofd-box) {
    height: calc(100vh - 60px) !important;
  }
}

::v-deep(.textareaInput) {
  textarea {
    resize: none !important;
    box-shadow: none !important;
  }
}
</style>